{"componentChunkName":"component---src-templates-post-jsx","path":"/[NextStep]3/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"e95f7d47-9b6c-58c1-a6db-3faa35ba2bfd","excerpt":"자바 웹 프로그래밍 Next Step - 박재성을 읽고 인용하고 정리하는 POST입니다. 3장은 로컬에서 웹 애플리케이션을 개발, 버전 관리 시스템에서 소스코드를 관리, 개발한 웹 애플리케이션을 원격 서버에 실제 배포하는 경험을 하고, 구현할 질문/답변 게시판에 대한 서비스 요구사항과 실습 요구사항을 제시한다.\n또한, HTTP 웹 서버를 직접 구현하는 경…","html":"<p><em>[자바 웹 프로그래밍 Next Step - 박재성]을 읽고 인용하고 정리하는 POST입니다.</em></p>\n<blockquote>\n<p>3장은 로컬에서 웹 애플리케이션을 개발, 버전 관리 시스템에서 소스코드를 관리, 개발한 웹 애플리케이션을 원격 서버에 실제 배포하는 경험을 하고, 구현할 질문/답변 게시판에 대한 서비스 요구사항과 실습 요구사항을 제시한다.\n또한, HTTP 웹 서버를 직접 구현하는 경험을 함으로써 웹 클라이언트와 서버 간 데이터를 어떻게 주고 받는지에 대해 학습한다.</p>\n</blockquote>\n<h2>🚩 서비스 요구사항</h2>\n<p><em>질문/답변 게시판</em></p>\n<h3>🔧 질문 목록 화면</h3>\n<ul>\n<li>회원가입</li>\n<li>로그인</li>\n<li>로그아웃</li>\n<li>개인정보 수정</li>\n<li>질문하기</li>\n<li>\n<p>각 질문 제목을 클릭하여 상세보기 화면으로 이동</p>\n<ul>\n<li>답변 추가, 질문과 답변의 수정/삭제</li>\n</ul>\n</li>\n</ul>\n<hr>\n<h2>🚩 로컬 개발 환경 구축</h2>\n<p><em>자바 8버전 &#x26; Intellij 통합 개발 환경</em></p>\n<p><a href=\"https://github.com/slipp/web-application-server\">https://github.com/slipp/web-application-server</a>, <a href=\"https://www.youtube.com/watch?v=5hjYe_PggJI\">https://www.youtube.com/watch?v=5hjYe_PggJI</a> 참고!</p>\n<hr>\n<h2>🚩 원격 서버에 배포</h2>\n<p><em>애자일 프로세스의 접근 방식</em>\n: 현 시점에 가장 가치있는, 동작하는 소프트웨어를 만드는 것을 원칙으로 하는 방식이다.</p>\n<p>로컬 개발 환경을 구축한 후 바로 실습 단계를 진행할 수 있지만 실습을 진행하기 전에 먼저 HTTP 웹 서버를 원격 서버에 배포해보자. 이러한 경험을 통해 터미널 환경에서 작업하는 것에 익숙해지도록 한다.\n<a href=\"https://opentutorials.org/module/1946\">https://opentutorials.org/module/1946</a> 참고하여 AWS에 대한 회원가입, 우분투 운영체제 설치, SSH를 통한 접근을 진행할 수 있다.</p>\n<h3>🔧 요구사항</h3>\n<p>로컬 개발 환경에 설치한 HTTP 웹 서버를 물리적으로 떨어져 있는 원격 서버에 배포해 정상적으로 동작하는지 테스트한다.</p>\n<hr>\n<h2>🚩 웹 서버 실습</h2>\n<h3>🔧 실습 환경 세팅 및 소스코드 분석</h3>\n<p>실습으로 진행할 HTTP 웹 서버는 앞의 로컬 개발 환경에서 세팅한 Git 저장소의 <strong>master</strong> 브랜치에서 시작하면 된다.</p>\n<p>실습 HTTP 웹 서버의 핵심이 되는 코드는 <code class=\"language-text\">webserver</code> 패키지의 <code class=\"language-text\">WebServer</code>, <code class=\"language-text\">RequestHandler</code> 클래스이다.</p>\n<ul>\n<li><code class=\"language-text\">WebServer</code> 클래스는 웹 서버를 시작하고, 사용자의 요청이 있을 때까지 대기 상태에 있다가 사용자 요청이 있을 경우 해당 요청을 <code class=\"language-text\">RequestHandler</code> 클래스에 위임하는 역할을 수행한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">// in WebServer.java\ntry (ServerSocket listenSocket = new ServerSocket(port)) {\n  log.info(&quot;Web Application Server started {} port.&quot;, port);\n\n  // 클라이언트가 연결될때까지 대기한다.\n  Socket connection;\n  while ((connection = listenSocket.accept()) != null) {\n      RequestHandler requestHandler = new RequestHandler(connection);\n      requestHandler.start();\n  }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>사용자 요청이 발생할 때까지 대기 상태에 있도록 지원하는 역할은 자바에 포함되어 있는 <code class=\"language-text\">ServerSocket</code> 클래스가 담당한다. </li>\n<li>사용자 요청이 발생하는 순간 클라이언트와 연결을 담당하는 <code class=\"language-text\">Socket</code> 을 <code class=\"language-text\">RequestHandler</code> 에 전달하면서 새로운 스레드를 실행하는 방식으로 <strong>멀티스레드 프로그래밍</strong>을 지원한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">// in RequestHandler.java\npackage webserver;\n\nimport java.io.DataOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.Socket;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class RequestHandler extends Thread {\n    private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);\n\n    private Socket connection;\n\n    public RequestHandler(Socket connectionSocket) {\n        this.connection = connectionSocket;\n    }\n\n    public void run() {\n        log.debug(&quot;New Client Connect! Connected IP : {}, Port : {}&quot;, connection.getInetAddress(),\n                connection.getPort());\n\n        try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {\n            // TODO 사용자 요청에 대한 처리는 이 곳에 구현하면 된다.\n            DataOutputStream dos = new DataOutputStream(out);\n            byte[] body = &quot;Hello World&quot;.getBytes();\n            response200Header(dos, body.length);\n            responseBody(dos, body);\n        } catch (IOException e) {\n            log.error(e.getMessage());\n        }\n    }\n\n    private void response200Header(DataOutputStream dos, int lengthOfBodyContent) {\n        try {\n            dos.writeBytes(&quot;HTTP/1.1 200 OK \\r\\n&quot;);\n            dos.writeBytes(&quot;Content-Type: text/html;charset=utf-8\\r\\n&quot;);\n            dos.writeBytes(&quot;Content-Length: &quot; + lengthOfBodyContent + &quot;\\r\\n&quot;);\n            dos.writeBytes(&quot;\\r\\n&quot;);\n        } catch (IOException e) {\n            log.error(e.getMessage());\n        }\n    }\n\n    private void responseBody(DataOutputStream dos, byte[] body) {\n        try {\n            dos.write(body, 0, body.length);\n            dos.flush();\n        } catch (IOException e) {\n            log.error(e.getMessage());\n        }\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">RequestHandler</code> 클래스는 <code class=\"language-text\">Thread</code> 를 상속하고, <strong>사용자의 요청에 대한 처리와 응답에 대한 처리를 담당하는 클래스</strong>이다.</li>\n<li>\n<p>앞으로의 모든 실습은 <code class=\"language-text\">RequestHandler</code> 클래스의 <code class=\"language-text\">run()</code> 메소드에서 구현할 수 있다.</p>\n<ul>\n<li>해당 메소드의 복잡도가 증가하는 경우, 새로운 클래스 또는 메소드로 분리하는 방식으로 리팩토링을 수행할 수 있다.</li>\n</ul>\n</li>\n<li><code class=\"language-text\">InputStream</code> : 클라이언트(웹 브라우저)에서 서버로 요청을 보낼 때 전달되는 데이터를 담당</li>\n<li>\n<p><code class=\"language-text\">OutputStream</code> : 서버에서 클라이언트에 응답을 보낼 때 전달되는 데이터를 담당</p>\n<ul>\n<li>웹 서버 입장에서 이해!</li>\n</ul>\n</li>\n</ul>\n<p>전체적인 흐름은,</p>\n<ul>\n<li><code class=\"language-text\">브라우저</code> 와 <code class=\"language-text\">WebServer의 RequestHandler</code> 는 <code class=\"language-text\">Socket</code> 이라는 통로로 통신한다.</li>\n<li>해당 통로의 <code class=\"language-text\">InputStream</code> &#x26; <code class=\"language-text\">OutputStream</code> 수단을 통해 데이터를 주고 받는다.</li>\n</ul>\n<blockquote>\n<p>\"프로그래밍 실행 중 발생하는 로그 메세지를 주의 깊게 살펴보는 것은 좋은 습관 중 하나이다.\"</p>\n</blockquote>\n<h3>🔧 실습 요구사항</h3>\n<p><strong>요구사항 1 - index.html 응답하기</strong><br/>\n: 현재 HTTP 웹 서버에 접속하면 무조건 \"Hello World\" 라는 문구만 뜬다. 이를 <code class=\"language-text\">http://localhost:8080/index.html</code> 로 접속했을 때, <code class=\"language-text\">index.html</code> 파일을 응답할 수 있도록 한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\"> try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {\n  // TODO 사용자 요청에 대한 처리는 이 곳에 구현하면 된다.\n  BufferedReader br = new BufferedReader(new InputStreamReader(in));\n\n  String line = br.readLine();\n  if (line == null) {return ;}\n  String[] tokens = line.split(&quot; &quot;);\n\n  while (!&quot;&quot;.equals(line)) {\n      line = br.readLine();\n  }\n\n  byte[] body = Files.readAllBytes(new File(&quot;./webapp&quot; + tokens[1]).toPath());\n  // byte[] body = &quot;Hello World&quot;.getBytes();\n\n  DataOutputStream dos = new DataOutputStream(out);\n  response200Header(dos, body.length);\n  responseBody(dos, body);\n} catch (IOException e) {\n  log.error(e.getMessage());\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">InputStream</code> , 즉 클라이언트가 보내는 요청을 한 줄 단위로 읽기 위해 <code class=\"language-text\">BufferedReader</code> 를 사용한다.</li>\n<li><code class=\"language-text\">null</code> 인 경우는 <code class=\"language-text\">return</code></li>\n<li><code class=\"language-text\">line</code> 을 <strong>\" \"</strong> 단위로 잘라 저장하고, <code class=\"language-text\">GET /index.html HTTP/1.1</code> 같은 형식이므로 <code class=\"language-text\">token[1]</code> 에 요청하는 파일의 정보가 담긴다.</li>\n<li>해당 파일 데이터를 <code class=\"language-text\">byte[]</code> 로 읽어 <code class=\"language-text\">response</code> 에 전달한다.</li>\n</ul>\n<p><strong>요구사항 2 - GET 방식으로 회원가입하기</strong><br/>\n: 회원가입 메뉴를 클릭하면 <a href=\"http://localhost:8080/user/form.html\">http://localhost:8080/user/form.html</a> 로 이동하면서 회원가입이 가능하다. 회원가입을 수행하면 다음과 같은 형태로 사용자 입력값이 서버에 전달된다.</p>\n<deckgo-highlight-code language=\"bash\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">/user/create?userId=javajigi&amp;password=password&amp;name=JaeSung&amp;email=javajigi%40slipp.net</code>\n        </deckgo-highlight-code>\n<p>HTML과 URL을 비교하고 사용자 입력 값을 파싱해 <code class=\"language-text\">model.User</code> 클래스에 저장한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">if (url.startsWith(&quot;/user/create&quot;)) {\n    int index = url.indexOf(&quot;?&quot;);\n    if (index != -1) {\n        Map&lt;String, String&gt; map = HttpRequestUtils.parseQueryString(url.substring(index+1));\n        User user = new User(map.get(&quot;userId&quot;), map.get(&quot;password&quot;), map.get(&quot;name&quot;), map.get(&quot;email&quot;));\n        System.out.println(user);\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>URL이 <code class=\"language-text\">/user/create</code> 로 시작하는 경우, 회원가입 요청이다.</li>\n<li>쿼리 문자열을 (이름, 값) 과 같은 형태로 분석하는 <code class=\"language-text\">parseQueryString</code> 을 이용하여 파라미터로부터 사용자 입력 값을 파싱한다.</li>\n<li>파싱한 값을 <code class=\"language-text\">User</code> 객체에 담는다.</li>\n<li>그 다음은 어떻게 ...</li>\n</ul>\n<p><strong>요구사항 3 - POST 방식으로 회원가입하기</strong><br/>\n: <a href=\"http://localhost:8080/user/form.html\">http://localhost:8080/user/form.html</a> 파일의 <code class=\"language-text\">form</code> 태그 메소드를 <strong><code class=\"language-text\">POST</code></strong> 로 수정한 후 회원가입을 구현한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">else if (tokens[0].equals(&quot;POST&quot;)) {\n    while(!line.equals(&quot;&quot;)) {\n        line = br.readLine();\n        if (line.contains(&quot;Content-Length&quot;)) {\n            String[] content = line.split(&quot;:&quot;);\n            contLength = Integer.parseInt(content[1].trim());\n        }\n    }\n    String body = IOUtils.readData(br, contLength);\n    Map&lt;String, String&gt; map = HttpRequestUtils.parseQueryString(body);\n    User user = new User(map.get(&quot;userId&quot;), map.get(&quot;password&quot;), map.get(&quot;name&quot;), map.get(&quot;email&quot;));\n    System.out.println(user);\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">/user/create</code> 분기에서 걸러지고, <code class=\"language-text\">GET</code> or <code class=\"language-text\">POST</code> 이므로 한 번 더 분기를 나눈다.</li>\n<li>\n<p>HTTP header와 body 사이에 빈 공백이 존재한다고 했으므로, 그 전까지 HTTP 요청을 읽으면서, <code class=\"language-text\">Content-Length</code> 값을 탐색한다.</p>\n<ul>\n<li>이떄, <code class=\"language-text\">Content-Length: 55</code> 와 같은 형식이라 <code class=\"language-text\">content[1]</code> 의 첫번째 자리에 공백이 포함되므로 <code class=\"language-text\">trim()</code> 을 이용해 이를 제거한다.</li>\n</ul>\n</li>\n<li><code class=\"language-text\">IOUtils.readData</code> 에 <code class=\"language-text\">reader</code> 와 <code class=\"language-text\">size</code> 를 주고 데이터를 읽고 <code class=\"language-text\">GET</code> 과 동일하게 사용자 입력 값을 파싱한다.</li>\n</ul>\n<p><strong>요구사항 4 - 302 status code 적용</strong><br/>\n: 회원가입을 완료한 후 <code class=\"language-text\">/index.html</code> 로 이동하고 싶다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">response302Header(dos, &quot;/index.html&quot;);\n\n...\n\nprivate void response302Header(DataOutputStream dos, String url) {\n    try {\n        dos.writeBytes(&quot;HTTP/1.1 302 Redirect \\r\\n&quot;);\n        dos.writeBytes(&quot;Location: &quot; + url + &quot; \\r\\n&quot;);\n        dos.writeBytes(&quot;\\r\\n&quot;);\n    } catch (IOException e) {\n        log.error(e.getMessage());\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p><strong>302</strong> code는 3XX Redirection 클래스에 속하는 HTTP 상태코드이다.</p>\n<ul>\n<li>클라이언트를 지정된 위치로 이동시키거나 참조하게 하는 등의 동작을 수행한다.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/HTTP_302\">참고1</a>, <a href=\"https://nsinc.tistory.com/168\">참고2</a></li>\n</ul>\n</li>\n</ul>\n<p><strong>요구사항 5 - 로그인하기</strong><br/>\n: 로그인 메뉴를 클릭하면 <code class=\"language-text\">~/user/login.html</code> 로 이동해 로그인할 수 있다. 성공하면 <code class=\"language-text\">/index.html</code> 로 이동하고, 그렇지 않으면 <code class=\"language-text\">/user/login_failed.html</code> 로 이동해야 한다.</p>\n<p>앞에서 회원가입한 사용자로 로그인할 수 있어야 한다. 로그인 성공 시, 쿠키를 활용해 로그인 상태를 유지할 수 있어야 한다. 로그인이 성공할 경우 요청 헤더의 Cookie 헤더 값이 <code class=\"language-text\">logined=true</code>, 실패할 경우 <code class=\"language-text\">logined=false</code> 로 전달되어야 한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">else if (url.equals(&quot;/user/login&quot;)) {\n    if (tokens[0].equals(&quot;POST&quot;)) {\n        while(!line.equals(&quot;&quot;)) {\n            line = br.readLine();\n            log.debug(&quot;Header : {}&quot;, line);\n            if (line.contains(&quot;Content-Length&quot;)) {\n                String[] content = line.split(&quot;:&quot;);\n                contLength= Integer.parseInt(content[1].trim());\n            }\n        }\n        String body = IOUtils.readData(br, contLength);\n        Map&lt;String, String&gt; map = HttpRequestUtils.parseQueryString(body);\n        User user = DataBase.findUserById(map.get(&quot;userId&quot;));\n        log.debug(&quot;User : {}&quot;, user);\n        if (user == null) {\n            responseFail(dos, &quot;/user/login_failed.html&quot;);\n            return;\n        }\n        if (user.getPassword().equals(map.get(&quot;password&quot;))) {\n            response302Logined(dos);\n        } else {\n            responseFail(dos, &quot;/user/login_failed.html&quot;);\n            return;\n        }\n    }\n}\n\nprivate void response302Logined(DataOutputStream dos) {\n    try {\n        dos.writeBytes(&quot;HTTP/1.1 302 Redirect \\r\\n&quot;);\n        dos.writeBytes(&quot;Location: /index.html \\r\\n&quot;);\n        dos.writeBytes(&quot;Set-Cookie: logined=true \\r\\n&quot;);\n        dos.writeBytes(&quot;\\r\\n&quot;);\n    } catch (IOException e) {\n        log.error(e.getMessage());\n    }\n}\n\nprivate void responseFail(DataOutputStream dos, String url) throws IOException {\n    byte[] body = Files.readAllBytes(new File(&quot;./webapp&quot; + url).toPath());\n\n    response200Header(dos, body.length);\n    responseBody(dos, body);\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">/user/login</code> 에 <strong>POST</strong>를 보내는 경우, HTTP body를 읽어 사용자 입력 값을 추출한다.</li>\n<li>DB에 저장되어 있는 값과 비교한 후, 각 경우에 맞게 response를 전달한다.</li>\n</ul>\n<p><strong>요구사항 6 - 사용자 목록 출력</strong><br/>\n: 사용자가 로그인 상태인 경우 <code class=\"language-text\">http://localhost:8080/user/list</code> 로 접근했을 때 사용자 목록을 출력한다. 로그인하지 않은 상태라면 <code class=\"language-text\">login.html</code> 로 이동한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">else if (url.equals(&quot;/user/list&quot;)) {\n    if (tokens[0].equals(&quot;GET&quot;)) {\n        while(!line.equals(&quot;&quot;)) {\n            line = br.readLine();\n            log.debug(&quot;Header : {}&quot;, line);\n            if (line.contains(&quot;Cookie&quot;)) {\n                login = isLogin(line);\n            }\n        }\n        if (!login) {\n            responseFail(dos, &quot;/user/login.html&quot;);\n            return;\n        }\n        Collection&lt;User&gt; users = DataBase.findAll();\n        StringBuilder sb = new StringBuilder();\n        sb.append(&quot;&lt;h1&gt;회원 목록&lt;/h1&gt;&quot;);\n        for (User user : users) {\n            sb.append(&quot;&lt;p&gt;&quot; + user.getUserId() + &quot;&lt;/p&gt;&quot;);\n            sb.append(&quot;&lt;p&gt;&quot; + user.getName() + &quot;&lt;/p&gt;&quot;);\n            sb.append(&quot;&lt;p&gt;&quot; + user.getEmail() + &quot;&lt;/p&gt;&quot;);\n        }\n        sb.append(&quot;&lt;h2&gt;목록 끝&lt;/h2&gt;&quot;);\n        byte[] body = sb.toString().getBytes();\n        response200Header(dos, body.length);\n        responseBody(dos, body);\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p><code class=\"language-text\">Cookie</code> 값을 가져와 로그인한 사용자인지 판단한다.</p>\n<ul>\n<li>로그인하지 않은 경우 <code class=\"language-text\">login.html</code> 을 전달한다.</li>\n<li><code class=\"language-text\">Database.findAll()</code> 로 회원가입된 모든 사용자를 가져온다.</li>\n<li><code class=\"language-text\">StringBuilder</code> 를 이용해 출력할 HTML code를 작성하고, 이를 response한다.</li>\n</ul>\n</li>\n</ul>\n<blockquote>\n<p><strong>String은 불변 객체</strong>이다. 2개의 String 객체가 있을 때, 두 객체를 더하는 연산은 새로운 String을 생성한다. 이 때, <strong>메모리 할당과 해제를 발생</strong>시켜 더하는 연산이 많아질수록 성능적으로 좋지 않다.\n따라서, 문자열을 더할 때 새로운 객체를 생성하는 것이 아닌 기존의 데이터에 더하는 방식을 사용하는 <strong><code class=\"language-text\">StringBuilder</code></strong> 클래스가 생겨났다.</p>\n</blockquote>\n<p><strong>요구사항 7 - CSS 지원하기</strong><br/>\n: CSS 파일을 지원하도록 구현한다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">else if (url.endsWith(&quot;.css&quot;)) {\n    byte[] body = Files.readAllBytes(new File(&quot;./webapp&quot; + url).toPath());\n    response200CssHeader(dos, body.length);\n    responseBody(dos, body);\n}\n\n...\n\nprivate void response200CssHeader(DataOutputStream dos, int length) {\n    try {\n        dos.writeBytes(&quot;HTTP/1.1 200 OK \\r\\n&quot;);\n        dos.writeBytes(&quot;Content-Type: text/css\\r\\n&quot;);\n        dos.writeBytes(&quot;Content-Length: &quot; + length + &quot;\\r\\n&quot;);\n        dos.writeBytes(&quot;\\r\\n&quot;);\n    } catch (IOException e) {\n        log.error(e.getMessage());\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>HTTP 요청의 header에 <code class=\"language-text\">./css/style.css</code> 와 같이 날라오기에, <code class=\"language-text\">endsWith()</code> 메소드를 사용해 이를 추출한다.</li>\n<li><code class=\"language-text\">Content-Type</code> 이 <code class=\"language-text\">text/css</code> 로 달라진 것을 확인할 수 있다.</li>\n</ul>\n<hr>\n<h2>🚩 추가 학습 자료</h2>\n<h3>🔧 Git과 Github</h3>\n<p><strong>Git</strong><br/>\n: 최근에 가장 많이 사용하는 버전 관리 시스템(Version Control System) 의 한 종류, VCS에 대한 기본 기능을 제공하는 도구이다.</p>\n<p><strong>Github</strong><br/>\n: Git이 제공하는 기능과 더불어 개발자들이 유용하게 사용할 수 있는 추가적인 기능을 제공하는 웹 애플리케이션이다.</p>\n<p>참고\n<a href=\"http://pcottle.github.io/learnGitBranching\">브랜치 rebase 등을 배우는 실습</a>\n<a href=\"http://www.sourcetreeapp.com\">GUI 도구</a></p>\n<h3>🔧 빌드 도구 메이븐</h3>\n<p><strong>빌드 도구</strong><br/>\n: 프로젝트와 관련한 설정을 관리하면서 소스코드(프로덕션, 테스트)에 대한 컴파일, 컴파일을 위해 필요한 라이브러리 관리, 테스트, 배포를 위한 패킹 작업 등의 작업을 자동화할 수 있도록 지원하는 도구</p>\n<ul>\n<li>프로젝트 디렉토리 구조와 의존성 라이브러리를 관리하므로, 프로젝트를 통합 개발 도구 프로젝트로 변환하는 것도 가능하다.</li>\n<li>웹 애플리케이션 개발에서 발생하는 단순, 반복적인 작업을 자동화할 수 있다.</li>\n<li>간단한 배포 작업까지 수행할 수 있다.</li>\n</ul>\n<p><strong>Maven (메이븐)과 Gradle (그래들)</strong><br/>\n<strong>메이븐</strong><br/>\n: 자바 진영에서 더 오랫 동안 사용해온 빌드 도구로, 설정 파일을 <strong>XML</strong>로 작성한다.</p>\n<ul>\n<li><strong>XML</strong>을 사용하기에 프로젝트의 크기가 커질수록 내용이 길어지고 가독성이 떨어진다.</li>\n</ul>\n<p><strong>그래들</strong><br/>\n: 최근 인기도가 높아지는 빌드 도구로, <code class=\"language-text\">그루비</code> 라는 언어를 기반으로 설정 파일을 관리하여 설정 파일에 대한 유연성도 높고, 코딩량도 메이븐의 <strong>XML</strong>에 비해 적다.</p>\n<ul>\n<li>빌드 속도가 메이븐에 비해 10~100배가량 빠르다.</li>\n<li>길이와 가독성 측면에서 효율적이다.</li>\n</ul>\n<p>두 빌드 도구의 기본 개념은 비슷한 점이 많아, 하나의 빌드 도구만 익히면 다른 빌드 도구에 대한 학습 비용도 낮다. </p>\n<h3>🔧 디버깅을 위한 로깅(logging)</h3>\n<p>개발자는 다음과 같은 목적으로 수많은 메세지를 출력한다.</p>\n<ul>\n<li>애플리케이션이 정상적으로 동작하는지 확인하기 위한 목적</li>\n<li>애플리케이션에 문제가 발생했을 때 원인을 파악하기 위한 디버깅 목적</li>\n</ul>\n<p>이때, 친숙한 <code class=\"language-text\">System.out.println()</code> 으로 출력하는데, 이는 <strong>애플리케이션의 성능을 저하</strong>시키는 원인이다.</p>\n<ul>\n<li>이를 이용해 디버깅 메세지를 출력하면 파일로 메세지가 출력하게 되는데, 파일에 메세지를 출력하는 작업은 상당한 비용이 발생한다.</li>\n</ul>\n<p><strong>logging 라이브러리</strong><br/>\n이와 같은 단점을 보완하기 위해 <strong>logging 라이브러리</strong>가 등장했다. 자바 진영에서 많이 사용하는 로깅 라이브러리는 <code class=\"language-text\">Logback</code> 이다. </p>\n<p>자바 진영에는 많은 로깅 라이브러리 구현체가 존재하는데, 더 좋은 구현체가 등장할 때마다 전체 소스코드에서 로깅 라이브러리 구현 부분을 수정하는 어려움이 있다. 이를 해결하기 위해 <code class=\"language-text\">SLF4J</code> 라는 라이브러리를 활용해 로깅 API에 대한 창구를 일원화했다.</p>\n<ul>\n<li>즉, 자바 소스코드는 <code class=\"language-text\">SLF4J</code> 라이브러리를 사용해 디버깅 메세지를 남기면 실제로 디버깅 메세지를 출력하는 구현체는 <code class=\"language-text\">Log4J</code>, <code class=\"language-text\">Logback</code> 이 담당하는 방식이다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nprivate static final Logger log = LoggerFactory.getLogger(RequestHandler.class);</code>\n        </deckgo-highlight-code>\n<ul>\n<li>해당 프로젝트는 로깅 구현체로 <code class=\"language-text\">Logback</code> 라이브러리를 사용한다. 하지만 이를 직접 사용하지 않고 <code class=\"language-text\">SLF4J</code> 를 import하고 있다.</li>\n<li><code class=\"language-text\">Logback</code> 라이브러리에 대한 구현체는 메이븐 설정 파일인 <code class=\"language-text\">pom.xml</code> 에서 설정하고 있다.</li>\n</ul>\n<p><strong>로그 레벨</strong><br/>\n로깅 라이브러리는 메세지 출력 여부를 <strong>로그 레벨</strong>을 통해 관리한다.</p>\n<ul>\n<li><code class=\"language-text\">TRACE</code> = <code class=\"language-text\">log.trace()</code>, <code class=\"language-text\">DEBUG</code> = <code class=\"language-text\">log.debug()</code>, <code class=\"language-text\">INFO</code> = <code class=\"language-text\">log.info()</code>, <code class=\"language-text\">WARN</code> = <code class=\"language-text\">log.warn()</code>, <code class=\"language-text\">ERROR</code> = <code class=\"language-text\">log.error()</code></li>\n<li>\n<p>TRACE &#x3C; DEBUG &#x3C; INFO &#x3C; WARN &#x3C; ERROR 순으로 높아진다.</p>\n<ul>\n<li>레벨이 높을 수록 출력되는 메세지는 적어지고, 낮을 수록 더 많은 로깅 레벨이 출력된다.</li>\n</ul>\n</li>\n<li>각 메세지에 대한 로그 레벨은 로깅 메세지를 구현할 때 결정된다.</li>\n</ul>\n<p><strong>로그 메세지 생성</strong><br/>\n로그 메세지 출력 시 다음과 같은 메세지 구현 방식이 일반적이다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">log.debug(&quot;New Client Connect! Connected IP : &quot; + connection.getInetAddress() + &quot;, Port : &quot; + conneciton.getPort());</code>\n        </deckgo-highlight-code>\n<ul>\n<li>하지만 위와 같은 방식은 로그 레벨이 <code class=\"language-text\">INFO</code> 나 <code class=\"language-text\">WARN</code> 인 경우 굳이 해당 메소드에 인자 전달을 위해 문자열을 더하는 부분이 실행될 필요가 없다. (아까 위에서 <code class=\"language-text\">StringBuilder</code> 를 사용하는 이유와 동일)</li>\n<li><code class=\"language-text\">SLF4J</code> 는 이러한 단점 보완을 위해 동적인 메세지를 구현하는 별도의 메소드를 제공한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">log.debug(&quot;New Client Connect! Connected IP : {}, Port : {}&quot;, connection.getInetAddress(), conneciton.getPort());</code>\n        </deckgo-highlight-code>\n<ul>\n<li>위 방식으로 <code class=\"language-text\">debug()</code> 메소드에서 로그 레벨에 따라 메세지를 더할 필요가 있는지의 여부를 판단하게 된다.</li>\n</ul>\n<p><code class=\"language-text\">Logback</code> 의 로그 레벨과 메세지 형식에 대한 설정 파일은 <code class=\"language-text\">logback.xml</code> 이며, 이를 통해 출력되는 로그 메세지의 패턴을 변경할 수 있다.</p>\n<blockquote>\n<p>Log4j. SLF4J 라이브러리별 템플릿 또한 존재해, 단순 반복적으로 발생하는 코드를 추가하여 개발 생산성을 높이는 데 도움이 될 수 있다.</p>\n</blockquote>\n<h2>📕 출처</h2>\n<p><strong>자바 웹 프로그래밍 Next Step : 하나씩 벗겨가는 양파껍질 학습법</strong> - 박재성</p>","frontmatter":{"title":"📖 3장 개발 환경 구축 및 웹 서버 실습 요구사항","date":"January 25, 2022","update":"January 25, 2022","tags":["Java","Refactoring","Framework"],"series":"📖 자바 웹 프로그래밍 Next Step"},"fields":{"slug":"/[NextStep]3/","readingTime":{"minutes":21.625}}},"seriesList":{"edges":[{"node":{"id":"f9691a13-3a27-5449-812b-5819a032b5cf","fields":{"slug":"/[NextStep]1/"},"frontmatter":{"title":"📖 1장 첫 번째 양파 껍질 벗기기"}}},{"node":{"id":"0a455dd6-0b0a-5012-adf7-ca17d9590acd","fields":{"slug":"/[NextStep]2/"},"frontmatter":{"title":"📖 2장 문자열 계산기 구현을 통한 테스트와 리팩토링"}}},{"node":{"id":"e95f7d47-9b6c-58c1-a6db-3faa35ba2bfd","fields":{"slug":"/[NextStep]3/"},"frontmatter":{"title":"📖 3장 개발 환경 구축 및 웹 서버 실습 요구사항"}}},{"node":{"id":"f940f29a-3fda-5127-93a7-d4776e581630","fields":{"slug":"/[NextStep]4/"},"frontmatter":{"title":"📖 4장 HTTP 웹 서버 구현을 통해 HTTP 이해하기"}}},{"node":{"id":"e192a3a9-2352-50a1-81fa-c042806ea2a2","fields":{"slug":"/[NextStep]5/"},"frontmatter":{"title":"📖 5장 웹 서버 리팩토링, 서블릿 컨테이너와 서블릿의 관계"}}},{"node":{"id":"9197157a-75bc-5414-8292-da27dd69a4e1","fields":{"slug":"/[NextStep]6/"},"frontmatter":{"title":"📖 6장 서블릿/JSP를 활용해 동적인 웹 애플리케이션 개발하기"}}},{"node":{"id":"4eec34ae-1e1a-5d59-bcd1-ed5f37722bc9","fields":{"slug":"/[NextStep]7/"},"frontmatter":{"title":"📖 7장 DB를 활용해 데이터를 영구적으로 저장하기"}}},{"node":{"id":"b15cc289-ba13-5439-be9b-2ccce07b1516","fields":{"slug":"/[NextStep]8/"},"frontmatter":{"title":"📖 8장 AJAX를 활용해 새로고침 없이 데이터 갱신하기"}}},{"node":{"id":"7c85cb46-2df5-5972-8e38-24208d1e06b5","fields":{"slug":"/[NextStep]9/"},"frontmatter":{"title":"📖 9장 두번째 양파 껍질을 벗기기 위한 중간 점검"}}},{"node":{"id":"43d32ee6-419a-5f7f-a3d5-d720774977fc","fields":{"slug":"/[NextStep]10/"},"frontmatter":{"title":"📖 10장 새로운 MVC 프레임워크 구현을 통한 점진적 개선"}}},{"node":{"id":"168191bb-b6de-5d4d-9d33-b9b8183f3857","fields":{"slug":"/[NextStep]11/"},"frontmatter":{"title":"📖 11장 의존관계 주입(DI)을 통한 테스트하기 쉬운 코드 만들기"}}},{"node":{"id":"361fa9e9-c9e8-568d-8e23-3ccddd10537e","fields":{"slug":"/[NextStep]12/"},"frontmatter":{"title":"📖 12장 확장성 있는 DI 프레임워크로 개선"}}}]},"previous":{"fields":{"slug":"/[NextStep]2/"},"frontmatter":{"title":"📖 2장 문자열 계산기 구현을 통한 테스트와 리팩토링"}},"next":{"fields":{"slug":"/[NextStep]4/"},"frontmatter":{"title":"📖 4장 HTTP 웹 서버 구현을 통해 HTTP 이해하기"}}},"pageContext":{"id":"e95f7d47-9b6c-58c1-a6db-3faa35ba2bfd","series":"📖 자바 웹 프로그래밍 Next Step","previousPostId":"0a455dd6-0b0a-5012-adf7-ca17d9590acd","nextPostId":"f940f29a-3fda-5127-93a7-d4776e581630"}},"staticQueryHashes":[]}